package com.qf.day0614.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author UNIQ7xi
 * @Date 2023/6/15 15:02
 * @Version v1.8
 * 自定义 分布式锁  基于redis的setnx命令
 **/
@Component
public class RedisLock {
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 加锁
     */
    public void lock(String key){
        //1.调用setnx命令
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, new Date());
        if (flag){
            //申请分布式锁成功
            return;
        }else {
            while (true){
                // 让申请失败线程进入一个自旋结构,尝试再次申请
                Boolean f = redisTemplate.opsForValue().setIfAbsent(key, new Date());
                if (f){
                    return;
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 解锁
     */
    public void unlock(String key){
        //释放锁是把key删除
        redisTemplate.delete(key);

    }
}
